import { Calendar, dayjsLocalizer } from 'react-big-calendar';
import dayjs from "dayjs";
import { v4 as uuid } from 'uuid'
import 'dayjs/locale/zh-cn'
import 'react-big-calendar/lib/css/react-big-calendar.css';
import CalendarModal from "@/components/calendar/CalendarModal.tsx";
import {useEffect, useRef, useState} from 'react'
import zhCN from 'antd/es/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {Button, Card, Flex, Form, Input, DatePicker} from "antd";
import { upload, configData } from "@/api/calendar.ts";
import useConfigDataFile from "@/hooks/useConfigDataFile.ts";

const { RangePicker } = DatePicker;
// moment.locale('zh-cn'); // 设置为中文
dayjs.locale('zh-cn')
const localizer = dayjsLocalizer(dayjs);
moment.locale('zh-cn');

interface calendarModalMethod {
    showModal: () => void
    handleCancel: () => void
    handleOk: () => void
}


const BigCalendar = () => {
    const dateFormat = 'YYYY-MM-DD HH:mm';
    const [form] = Form.useForm()
    const [title, setTitle] = useState<string>('新增日程')
    const [events, setEvents] = useState<Array<{ uid: string, title: string, start: Date, end: Date }>>([])
    const { dataFile } = useConfigDataFile(JSON.stringify(events))
    const [uid, setUid] = useState<string>('')
    const [value] = useState<{ title: string, time:  dayjs.Dayjs[]}>({ title: '', time: [dayjs(dayjs(dayjs().format(dateFormat), dateFormat)) as dayjs.Dayjs, dayjs(dayjs(dayjs().format(dateFormat), dateFormat)) as dayjs.Dayjs]})
    const calendarModalRef = useRef(null)
    const getData =  () => {
        configData().then(res => {
            const { data } = res
            // setEvents(data)
            if (data && data.length !== 0) {
                data.map(item => {
                    item['start'] = new Date(item.start)
                    item['end'] = new Date(item.end)
                    return item
                })
            }
            setEvents(data)
        })
    }
    useEffect(() => {
        const btnGroup = document.getElementsByClassName('rbc-btn-group')
        const btnLeft = btnGroup[0].getElementsByTagName('button')
        const btnRight = btnGroup[1].getElementsByTagName('button')
        btnLeft[0].innerHTML = '本月'
        btnLeft[1].innerHTML = '上月'
        btnLeft[2].innerHTML = '下月'
        btnRight[0].innerHTML = '月'
        btnRight[1].innerHTML = '周'
        btnRight[2].innerHTML = '日'
        btnRight[3].innerHTML = '日程'
        getData()
    }, []);
    const open = (event: null | { uid: string, title: string, start: Date, end: Date }) => {
        if (event) {
            const data: { title: string, time: dayjs.Dayjs[] } = { title: event.title, time: [dayjs(dayjs(event.start).format(dateFormat), dateFormat), dayjs(dayjs(event.end).format(dateFormat), dateFormat)] }
            form.setFieldsValue(data)
            setUid(event.uid)
            setTitle('编辑日程')
        } else {
            setUid('')
            setTitle('新增日程')
            form.resetFields()
        }
        if (calendarModalRef.current) {
            (calendarModalRef.current as calendarModalMethod).showModal()
        }
    }
    const handleData = async (data: { uid: string, title: string, start: Date, end: Date }[]) => {
        setEvents(data)
        const formData = new FormData()
        formData.append('file', dataFile(JSON.stringify(data)))
        await upload(formData)
        form.resetFields()
        if (calendarModalRef.current) {
            (calendarModalRef.current as calendarModalMethod).handleOk()
        }
    }
    const onfinish = async (values: { title: string, time:  dayjs.Dayjs[]}) => {
        let data: Array<{ uid: string, title: string, start: Date, end: Date }> = []
        if (uid) {
            data = events.map(item => {
                if (item.uid === uid) {
                    item['title'] = values.title
                    item['start'] = values.time[0].toDate()
                    item['end'] = values.time[1].toDate()
                }
                return item
            })
        } else {
            data = [...events, { uid: uuid(), title: values.title, start: values.time[0].toDate(), end: values.time[1].toDate() }]
        }
        await handleData(data)
    }
    const del = async () => {
        const data = events.filter(item => item.uid !== uid)
        await handleData(data)
    }
    const handleCancel = () => {
        form.resetFields()
        if (calendarModalRef.current) {
            (calendarModalRef.current as calendarModalMethod).handleCancel()
        }
    }
    return (
        <Card title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>我的日程</span>
            <CalendarModal title={title} ref={calendarModalRef} content={
                <Form form={form} onFinish={onfinish} initialValues={value}>
                    <Form.Item label='时间' name='time' rules={[{ required: true, message: '请选择时间' }]}>
                        <RangePicker showTime={{ format: 'HH:mm' }} locale={zhCN} format={dateFormat} />
                    </Form.Item>
                    <Form.Item label='事件' name='title' rules={[{ required: true, message: '请填写事件' }]}>
                        <Input.TextArea />
                    </Form.Item>
                    <Form.Item>
                        <Flex gap='middle' wrap justify='end'>
                            <Button onClick={handleCancel}>取消</Button>
                            { uid ? <Button type='primary' danger onClick={del}>删除</Button> : null }
                            <Button type='primary' htmlType="submit">确定</Button>
                       </Flex>
                    </Form.Item>
                </Form>
            } btn={<Button type='link' onClick={() => open(null)}>新增</Button>} />
        </div>}>
            <div>
                <Calendar
                    localizer={localizer}
                    events={events}
                    startAccessor="start"
                    endAccessor="end"
                    style={{height: 500}}
                    onSelectEvent={(event: { title: string, start: Date, end: Date }) => open(event as { uid: string, title: string, start: Date, end: Date })}
                    onSelectSlot={slotInfo =>
                        alert(`你选择了: ${slotInfo.start.toLocaleString()} 到 ${slotInfo.end.toLocaleString()}`)
                    }
                />
            </div>
        </Card>
    )
};

export default BigCalendar;